const Parse = require('parse/node');
const UserObj = Parse.Object.extend("v5_user");
const RoleObj = Parse.Object.extend("v5_role");
const ParseHelper = require('../helpers/parse');
const ExcelService = require("./excel");
const moment = require('moment');
const _ = require('lodash');

/**
 * 用户管理服务 - 优化版本
 * 支持多角色管理：管理员、教师、学生
 * 支持权限管理和批量操作
 */

// 用户角色定义
const USER_ROLES = {
    ADMIN: 'admin',
    TEACHER: 'teacher',
    STUDENT: 'student'
};

// 权限定义
const PERMISSIONS = {
    // 用户管理权限
    USER_CREATE: 'user_create',
    USER_READ: 'user_read',
    USER_UPDATE: 'user_update',
    USER_DELETE: 'user_delete',
    USER_IMPORT: 'user_import',
    
    // 物料管理权限
    MATERIAL_CREATE: 'material_create',
    MATERIAL_READ: 'material_read',
    MATERIAL_UPDATE: 'material_update',
    MATERIAL_DELETE: 'material_delete',
    MATERIAL_IMPORT: 'material_import',
    
    // 审批权限
    APPROVE_APPLICATION: 'approve_application',
    APPROVE_REPAIR: 'approve_repair',
    
    // 柜子管理权限
    CABINET_MANAGE: 'cabinet_manage',
    CABINET_OPERATE: 'cabinet_operate',
    
    // 统计权限
    STATISTICS_VIEW: 'statistics_view',
    STATISTICS_EXPORT: 'statistics_export',
    
    // 白名单权限
    WHITELIST_MANAGE: 'whitelist_manage'
};

// 角色权限映射
const ROLE_PERMISSIONS = {
    [USER_ROLES.ADMIN]: Object.values(PERMISSIONS),
    [USER_ROLES.TEACHER]: [
        PERMISSIONS.USER_READ,
        PERMISSIONS.USER_IMPORT,
        PERMISSIONS.MATERIAL_READ,
        PERMISSIONS.APPROVE_APPLICATION,
        PERMISSIONS.APPROVE_REPAIR,
        PERMISSIONS.CABINET_OPERATE,
        PERMISSIONS.STATISTICS_VIEW,
        PERMISSIONS.WHITELIST_MANAGE
    ],
    [USER_ROLES.STUDENT]: [
        PERMISSIONS.MATERIAL_READ
    ]
};

/**
 * 创建用户
 * @param {Object} userData - 用户数据
 * @param {string} role - 用户角色
 * @returns {Promise<Object>} 创建结果
 */
async function createUser(userData, role = USER_ROLES.STUDENT) {
    try {
        // 验证用户数据
        if (!userData.username || !userData.showName) {
            throw new Error('用户名和姓名为必填项');
        }

        // 检查用户是否已存在
        const existingUser = await getUserByUsername(userData.username);
        if (existingUser) {
            throw new Error('用户名已存在');
        }

        // 创建用户对象
        const user = new UserObj();
        user.set('username', userData.username);
        user.set('showName', userData.showName);
        user.set('studentNumber', userData.studentNumber || userData.username);
        user.set('class_name', userData.class_name || '');
        user.set('phone', userData.phone || '');
        user.set('email', userData.email || '');
        user.set('role', role);
        user.set('isActive', true);
        user.set('createdAt', new Date());
        user.set('updatedAt', new Date());

        // 设置默认密码
        user.set('password', userData.password || userData.username);

        await user.save(null, { useMasterKey: true });
        
        // 创建Parse用户
        const parseUser = new Parse.User();
        parseUser.set('username', userData.username);
        parseUser.set('password', userData.password || userData.username);
        parseUser.set('showName', userData.showName);
        parseUser.set('role', role);
        
        await parseUser.signUp();

        return {
            success: true,
            user: ParseHelper.toJSON(user),
            message: '用户创建成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 批量创建用户
 * @param {Array} usersData - 用户数据数组
 * @param {string} role - 用户角色
 * @returns {Promise<Object>} 批量创建结果
 */
async function batchCreateUsers(usersData, role = USER_ROLES.STUDENT) {
    try {
        const results = {
            success: 0,
            failed: 0,
            errors: []
        };

        for (const userData of usersData) {
            const result = await createUser(userData, role);
            if (result.success) {
                results.success++;
            } else {
                results.failed++;
                results.errors.push({
                    username: userData.username,
                    error: result.error
                });
            }
        }

        return {
            success: true,
            results,
            message: `成功创建 ${results.success} 个用户，失败 ${results.failed} 个用户`
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取用户信息
 * @param {string} username - 用户名
 * @returns {Promise<Object>} 用户信息
 */
async function getUserByUsername(username) {
    try {
        const query = new Parse.Query(UserObj);
        query.equalTo('username', username);
        query.notEqualTo('isDeleted', true);
        
        const user = await query.first({ useMasterKey: true });
        return user ? ParseHelper.toJSON(user) : null;
    } catch (error) {
        throw new Error('获取用户信息失败: ' + error.message);
    }
}

/**
 * 更新用户信息
 * @param {string} userId - 用户ID
 * @param {Object} updateData - 更新数据
 * @returns {Promise<Object>} 更新结果
 */
async function updateUser(userId, updateData) {
    try {
        const user = UserObj.createWithoutData(userId);
        
        // 更新允许的字段
        const allowedFields = ['showName', 'studentNumber', 'class_name', 'phone', 'email', 'role', 'isActive'];
        allowedFields.forEach(field => {
            if (updateData[field] !== undefined) {
                user.set(field, updateData[field]);
            }
        });
        
        user.set('updatedAt', new Date());
        await user.save(null, { useMasterKey: true });

        return {
            success: true,
            message: '用户信息更新成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 删除用户
 * @param {string} userId - 用户ID
 * @returns {Promise<Object>} 删除结果
 */
async function deleteUser(userId) {
    try {
        const user = UserObj.createWithoutData(userId);
        user.set('isDeleted', true);
        user.set('deletedAt', new Date());
        
        await user.save(null, { useMasterKey: true });

        return {
            success: true,
            message: '用户删除成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 批量删除用户
 * @param {Array} userIds - 用户ID数组
 * @returns {Promise<Object>} 批量删除结果
 */
async function batchDeleteUsers(userIds) {
    try {
        const users = userIds.map(id => {
            const user = UserObj.createWithoutData(id);
            user.set('isDeleted', true);
            user.set('deletedAt', new Date());
            return user;
        });

        await Parse.Object.saveAll(users, { useMasterKey: true });

        return {
            success: true,
            message: `成功删除 ${userIds.length} 个用户`
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取用户列表
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 用户列表
 */
async function getUserList(options = {}) {
    try {
        const {
            role,
            page = 1,
            limit = 10,
            search,
            class_name,
            isActive,
            sortBy = 'createdAt',
            sortOrder = 'desc'
        } = options;

        const query = new Parse.Query(UserObj);
        query.notEqualTo('isDeleted', true);

        // 角色筛选
        if (role) {
            query.equalTo('role', role);
        }

        // 激活状态筛选
        if (isActive !== undefined) {
            query.equalTo('isActive', isActive);
        }

        // 班级筛选
        if (class_name) {
            query.equalTo('class_name', class_name);
        }

        // 搜索筛选
        if (search) {
            const searchQuery1 = new Parse.Query(UserObj);
            searchQuery1.contains('username', search);
            
            const searchQuery2 = new Parse.Query(UserObj);
            searchQuery2.contains('showName', search);
            
            const searchQuery3 = new Parse.Query(UserObj);
            searchQuery3.contains('studentNumber', search);
            
            query._orQuery([searchQuery1, searchQuery2, searchQuery3]);
        }

        // 排序
        if (sortOrder === 'desc') {
            query.descending(sortBy);
        } else {
            query.ascending(sortBy);
        }

        // 分页
        const skip = (page - 1) * limit;
        query.skip(skip);
        query.limit(limit);

        // 获取总数
        const countQuery = new Parse.Query(UserObj);
        countQuery.notEqualTo('isDeleted', true);
        if (role) countQuery.equalTo('role', role);
        if (isActive !== undefined) countQuery.equalTo('isActive', isActive);
        if (class_name) countQuery.equalTo('class_name', class_name);

        const [users, total] = await Promise.all([
            query.find({ useMasterKey: true }),
            countQuery.count({ useMasterKey: true })
        ]);

        return {
            success: true,
            users: users.map(user => ParseHelper.toJSON(user)),
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 重置用户密码
 * @param {string} userId - 用户ID
 * @param {string} newPassword - 新密码
 * @returns {Promise<Object>} 重置结果
 */
async function resetPassword(userId, newPassword) {
    try {
        // 更新v5_user表
        const user = UserObj.createWithoutData(userId);
        user.set('password', newPassword);
        user.set('updatedAt', new Date());
        await user.save(null, { useMasterKey: true });

        // 更新Parse User表
        const userQuery = new Parse.Query(Parse.User);
        const userObj = await userQuery.get(userId, { useMasterKey: true });
        if (userObj) {
            userObj.set('password', newPassword);
            await userObj.save(null, { useMasterKey: true });
        }

        return {
            success: true,
            message: '密码重置成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 检查用户权限
 * @param {string} userId - 用户ID
 * @param {string} permission - 权限名称
 * @returns {Promise<boolean>} 是否有权限
 */
async function checkPermission(userId, permission) {
    try {
        const user = await getUserByUsername(userId);
        if (!user) return false;

        const userRole = user.role;
        const rolePermissions = ROLE_PERMISSIONS[userRole] || [];
        
        return rolePermissions.includes(permission);
    } catch (error) {
        return false;
    }
}

/**
 * 获取用户权限列表
 * @param {string} userId - 用户ID
 * @returns {Promise<Array>} 权限列表
 */
async function getUserPermissions(userId) {
    try {
        const user = await getUserByUsername(userId);
        if (!user) return [];

        const userRole = user.role;
        return ROLE_PERMISSIONS[userRole] || [];
    } catch (error) {
        return [];
    }
}

/**
 * 导入用户Excel文件
 * @param {string} filePath - 文件路径
 * @param {Object} options - 导入选项
 * @returns {Promise<Object>} 导入结果
 */
async function importUsersFromExcel(filePath, options = {}) {
    try {
        const {
            nameRowNumber = 1,
            firstDataRowNumber = 2,
            fieldsMapping = {},
            role = USER_ROLES.STUDENT
        } = options;

        const usersData = await ExcelService.parseExcelFileFirstSheet(
            filePath,
            nameRowNumber,
            firstDataRowNumber
        );

        if (!usersData || usersData.length === 0) {
            throw new Error('Excel文件没有有效数据');
        }

        // 数据映射
        const mappedUsersData = usersData.map(userData => {
            const mappedData = {};
            Object.keys(userData).forEach(key => {
                const dbFieldName = fieldsMapping[key] || key;
                mappedData[dbFieldName] = userData[key];
            });
            return mappedData;
        });

        // 批量创建用户
        const result = await batchCreateUsers(mappedUsersData, role);
        
        return result;
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

module.exports = {
    createUser,
    batchCreateUsers,
    getUserByUsername,
    updateUser,
    deleteUser,
    batchDeleteUsers,
    getUserList,
    resetPassword,
    checkPermission,
    getUserPermissions,
    importUsersFromExcel,

};
